package org.gw.ylc.base.service;

import org.gw.ylc.base.context.RequestContextHolder;
import org.gw.ylc.base.model.Administrator;
import org.gw.ylc.base.repositories.AdministratorRepository;
import org.gw.ylc.base.util.PermissionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AdministratorService {
	@Autowired
	private AdministratorRepository administratorRepository;
	@Autowired
	private UserInfoService userInfoService;

	public Page<Administrator> query(String name, String department, Integer type, String app) {
		if (PermissionUtil.isSchoolAdmin()) {
			return administratorRepository.findByNameAndDepartmentAndType(PermissionUtil.toLikeString(name), department,
					type, app, RequestContextHolder.get().getPageRequest());
		}
		return null;
	}

	public void add(Administrator administrator) {
		if (PermissionUtil.isSchoolAdmin() && administrator.getType() != 3) {
			administratorRepository.save(administrator);
			userInfoService.removeFromCache(administrator.getEmployeeNo());
		}
	}

	public void update(Administrator administrator) {
		if (PermissionUtil.isSchoolAdmin() && administrator.getType() != 3) {
			administratorRepository.save(administrator);
			userInfoService.removeFromCache(administrator.getEmployeeNo());
		}
	}

	@Transactional
	public void delete(String id, String app) {
		if (PermissionUtil.isSchoolAdmin()) {
			Administrator admin = administratorRepository.findById(id);
			if (admin != null) {
				userInfoService.removeFromCache(admin.getEmployeeNo());
			}
			administratorRepository.deleteNormalAdmin(id, app);
		}
	}
}
